package com.wangmei.controller;

import com.wangmei.model.Product;

import com.wangmei.pojo.ByAtOnce;
import com.wangmei.pojo.OrderDetailPojo;
import com.wangmei.pojo.PayKUID;
import com.wangmei.pojo.UserSimplify;
import com.wangmei.service.ByCartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;
import unitTool.Dictionary;
import unitTool.JsonRsp;

import javax.servlet.http.*;
import java.io.PipedOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**.
 * .购物车
 */
@RequestMapping("/order")
@RestController
public class BuyCartController {

    @Autowired
    private ByCartService byCartService;
    /**
     *
     * @param uid
     * @return
     *
     *
     * 注意：ostate==0才是购物车状态
     */
    @ApiOperation("获得购物车")
    @RequestMapping(value = "/getCart",method = RequestMethod.POST)
    public JsonRsp getCart(
            @RequestParam("uid") int uid){
        try{
            return JsonRsp.success(byCartService.getBuyCartList(uid));
        }catch (Exception e){
            e.printStackTrace();
            return JsonRsp.fail(4000,"系统内部错误");}

    }



    /**
     * 删除购物车里的单个记录
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public JsonRsp delet(@RequestParam("detailid")int id){
        try{
            return JsonRsp.success(byCartService.deleteByKey(id),"success");
        }catch (Exception e){
            e.printStackTrace();
            return JsonRsp.fail(4000,"系统内部错误");
        }


    }

    /**
     * 购物车批量删除
     * @param ids
     * @return
     */
    @RequestMapping(value = "/deleteList",method = RequestMethod.POST)
    public JsonRsp deletList(@RequestBody List<Integer> ids){
        try{
            return JsonRsp.success(byCartService.deleteByKeyList(ids),"success");
        }catch (Exception e){
            e.printStackTrace();
            return JsonRsp.fail(4000,"系统内部错误");
        }

    }

    @RequestMapping(value = "/addToCart",method = RequestMethod.POST)
    public JsonRsp addToCart(
            @RequestParam("uid") int uid,
            @RequestParam("pid") int pid,
            @RequestParam(value = "num",defaultValue = "1")int num,
            @RequestParam(value = "kuid") int kuid,
            @RequestParam(value = "tprice") double tprice,//快递费
            HttpServletRequest request,
            HttpServletResponse response){
        try{
            int detailid=byCartService.addToCart(uid,pid,num,kuid,tprice);
            return JsonRsp.success(new HashMap<>(),"success");
        }catch (Exception e){
            e.printStackTrace();
            return JsonRsp.fail(4000,"系统内部错误");
        }
    }

    /**
     * 从购物车---->产品详细
     * 代码思路：
     * 往数据库添加新的记录：
     *                          注：issuccess = 0；表示未成功。
     *                            ： ostate为1：表示支付详情中
     *                            ：添加order_details的记录，oid确定
     * @param session           session
     * @param orderDetailPojos ：详细的
     * @return
     */
    @ApiOperation("购物车提交")
    @RequestMapping(value = "/goToBalance",method = RequestMethod.POST)
    public JsonRsp goTopay(HttpSession session
            ,@RequestBody OrderDetailPojo[] orderDetailPojos
//            ,@RequestParam(value = "addressid") int addressid
//            ,@RequestParam(value = "discount",defaultValue = "1") double discount
//            ,@RequestParam(value = "post") double post){
                                                        ){
        try{
            //获得当前用户
            UserSimplify userSimplify = (UserSimplify) session.getAttribute(Dictionary.SessionKey.CURRENT_USER);
            if (null == userSimplify)
                return JsonRsp.fail(1001,"登入超时");
            int uid = userSimplify.getUid();
            //插入新数据
            Map<String,Object> map = new HashMap<>();
//            map.put("addressid",addressid);
//            map.put("discount",discount);
//            map.put("post",post);
            map.put("uid",uid);
            String orderid = byCartService.addToPay(orderDetailPojos, map);

            //信息加入session
            List<PayKUID> payKUIDS =new ArrayList<>();//用户修改库存
            PayKUID record;
            StringBuilder detailids = new StringBuilder();
            int flag = 0;
            detailids.append("(");
            for(OrderDetailPojo odp : orderDetailPojos) {
                if(flag != 0)
                    detailids.append(",");
                flag++;
                detailids.append(odp.getDetailid());
                record = new PayKUID();
                record.setKuid(odp.getKuid());
                record.setNum(odp.getBuyNum());
                payKUIDS.add(record);
            }
            detailids.append(")");

            session.setAttribute(Dictionary.SessionKey.CURRENT_ORDER_DETA_KUID_NUM,payKUIDS);
            session.setAttribute(Dictionary.SessionKey.CURRENT_ORDER_ID,orderid);
            session.setAttribute(Dictionary.SessionKey.CURRENT_ORDER_DETAILS, detailids.toString());

            return JsonRsp.success(new HashMap<>(),"go to pay");
        }catch (Exception e){
            e.printStackTrace();
            return JsonRsp.fail(1000,"未知错误");
        }
    }
    @ApiOperation("获取待支付")
    @RequestMapping(value = "getDetailOrder",method=RequestMethod.POST)
    public JsonRsp getDetailOrder(HttpSession session,HttpServletRequest request){
        //获得登陆用户
        try {
            UserSimplify userSimplify = (UserSimplify) session.getAttribute(Dictionary.SessionKey.CURRENT_USER);
            if (null == userSimplify)
                return JsonRsp.fail(1001,"登入超时");
            int uid = userSimplify.getUid();
//            uid = 1;
            //测试！！！
            String oid = (String) session.getAttribute(Dictionary.SessionKey.CURRENT_ORDER_ID);
            /**
             * 获取返回数据
             * 包括orderid
             *      state = 1
             * 产品list
             *
             */
            Map<String,Object> remap = byCartService.getBuyCartDetailList(uid);
            //添加邮费
            List<OrderDetailPojo> orderDetal = (List<OrderDetailPojo>) remap.get("OrderDetailPojos");
            int tTotle = 0;

            for(OrderDetailPojo od :orderDetal) {
               tTotle += od.getTprice();
            }
            remap.put("tTotal",tTotle);
            return JsonRsp.success(remap);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonRsp.fail(1000, "系统内部错误");
        }
    }
    /**
     * 最后，已经点击了，支付，钱已经付了。。。
     * @param session
     * @param paymethod
     * @return
     */
    @ApiOperation("支付-->结束")
    @RequestMapping(value = "/payMoney", method=RequestMethod.POST)
    public JsonRsp payMoney(HttpSession session
            ,@RequestParam(value = "paymethod") int paymethod){
        try{
            /**
             * 将购物车的记录消除
             *
            */
            String detailids = (String) session.getAttribute(Dictionary.SessionKey.CURRENT_ORDER_DETAILS);
            String orderid = (String) session.getAttribute(Dictionary.SessionKey.CURRENT_ORDER_ID);
            List<PayKUID> kuidList = (List<PayKUID>) session.getAttribute(Dictionary.SessionKey.CURRENT_ORDER_DETA_KUID_NUM);
            byCartService.deletebuyCartitem(detailids,orderid,paymethod,kuidList);
            return JsonRsp.success("订单生成结束");
        }catch (Exception e){
            e.printStackTrace();
            return JsonRsp.fail(1000,"内部错误");
        }
    }
    @ApiOperation("提交详细信息-->支付")
    @RequestMapping(value = "/submitDetail", method=RequestMethod.GET)
    public JsonRsp payMoney(HttpSession session
            ,@RequestParam(value = "oid") String oid
            ,@RequestParam(value = "discount",defaultValue = "1") double discount//打折
            ,@RequestParam(value = "post",defaultValue = "0") double post//邮费
            ,@RequestParam(value = "total") double total//总价格
            ,@RequestParam(value = "paycode",required = false) String paycode//优惠卷
            ,@RequestParam(value = "addressid") int addressid ){

        try{
            session.setAttribute(Dictionary.SessionKey.CURRENT_ORDER_ID,oid);
            Map<String,Object> map = new HashMap<>();
            map.put("oid",oid);
            map.put("discount",discount);
            map.put("post",post);
            map.put("total",total);
            map.put("addressid",addressid);
            if(paycode==null || "".equals(paycode))
                map.put("paycode",null);
            else
                map.put("paycode",paycode);
            byCartService.readyToPay(map);
            return JsonRsp.success(new HashMap<>(),"success");
        }catch (Exception e){
            e.printStackTrace();
            return JsonRsp.fail(1001,"内部错误");
        }

    }
    @ApiOperation("获得最后的最后的数据")
    @RequestMapping(value = "/orderfinal", method=RequestMethod.POST)
    public JsonRsp orderFinal(HttpSession session){
        try {
            UserSimplify userSimplify = (UserSimplify) session.getAttribute(Dictionary.SessionKey.CURRENT_USER);
            if (null == userSimplify)
                return JsonRsp.fail(1001,"登入超时");
            int uid = userSimplify.getUid();
            Map<String,Object> map = new HashMap<>();
            map.put("uid",uid);
            return JsonRsp.success(byCartService.orderfinalsearch(map),"success");
        }catch (Exception e){
            e.printStackTrace();
            return JsonRsp.fail(123,"内部错误");
        }
    }

    @ApiOperation("立即支付")
    @RequestMapping(value = "/payontItem",method = RequestMethod.POST)
    public JsonRsp payitem(@RequestBody ByAtOnce orderDetailPojo, HttpSession session){
        try{
            UserSimplify userSimplify = (UserSimplify) session.getAttribute(Dictionary.SessionKey.CURRENT_USER);
            if (null == userSimplify)
                return JsonRsp.fail(1001,"登入超时");
            int uid = userSimplify.getUid();
            Map<String,Object> map = new HashMap<>();
            map.put("uid",uid);
            List<PayKUID> payKUIDS =new ArrayList<>();
            PayKUID record = new PayKUID();
            record.setKuid(orderDetailPojo.getKuid());
            record.setNum(orderDetailPojo.getBuyNum());
            payKUIDS.add(record);
            session.setAttribute(Dictionary.SessionKey.CURRENT_ORDER_DETA_KUID_NUM,payKUIDS);

            byCartService.limitToPay(orderDetailPojo,map);
            return JsonRsp.success(new HashMap<>(),"跳你");

        }catch(Exception e){
            e.printStackTrace();
            return JsonRsp.fail(100,"内部错误");
        }

    }
}
